package com.leyou.sms.utils;

import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import com.leyou.sms.config.SmsPropertie;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Random;
import java.util.concurrent.TimeUnit;

/**
 * @author huangxin
 * @date 2019/5/10-20:08
 */
@Component
@Slf4j
public class SmsUtils {
    @Autowired
    private SmsPropertie prop;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static final String KEY_PREFIX = "sms:phone:";
    //最小间隔时间
    private static final long SMS_MIN_INTERVAL = 60*1000;

    public SmsSingleSenderResult send(String phoneNumbers,String SmsSign,int templateId,String... params) {
        String key = KEY_PREFIX+phoneNumbers;
        //针对手机号限流
        //读取时间
        String lastTime = redisTemplate.opsForValue().get(key);
        if (StringUtils.isNotBlank(lastTime)){
            //间隔的时间
            Long interval = System.currentTimeMillis()-Long.valueOf(lastTime);

            if (interval<SMS_MIN_INTERVAL){
                //如果小于最小间隔时间
                log.info("[短信服务] 发送短信频率过高,手机号码:{}",phoneNumbers);
                return null;
            }
        }
        try {


            SmsSingleSender ssender = new SmsSingleSender(prop.getAppid(), prop.getAppkey());

            SmsSingleSenderResult resp = ssender.sendWithParam("86", phoneNumbers,
                    templateId, params, SmsSign, "", "");  // 签名参数未提供或者为空时，会使用默认签名发送短信
            //发送失败记录日志
            if (0!=resp.result) {
                log.info("[短信服务] 发送短信失败, phoneNumber:{},原因:{}",phoneNumbers,resp.errMsg);
            }

            //发送短信成功后,写入redis,指定超时时间为1分钟
            redisTemplate.opsForValue().set(key,String.valueOf(System.currentTimeMillis()),1, TimeUnit.MINUTES);

            return resp;
        } catch (Exception e) {
            log.info("[短信服务] 发送短信失败, phoneNumber:{},原因:{}",phoneNumbers,e);
            e.printStackTrace();
        }
        return null;
    }
}
